package com.wulinbus.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fancy.common.utils.Config;
import com.fancy.common.utils.RequestUtils;
import com.fancy.pay.alipay.config.AlipayConfig;
import com.fancy.pay.alipay.util.AlipayNotify;
import com.fancy.pay.alipay.util.AlipaySubmit;
import com.wulinbus.model.CreativeModel;
import com.wulinbus.model.CreativeOrderModel;
import com.wulinbus.service.CreativeOrderService;
import com.wulinbus.service.CreativeService;
import com.wulinbus.service.UserService;
import com.wulinbus.utils.CasUtil;

@Controller
public class AlipayController {
	
	@Resource
	private CreativeOrderService creativeOrderService;
	@Resource
	private CreativeService creativeService;
	@Resource
	private UserService userService;
	/**
	 * 日志记录器
	 */
	protected static final Logger logger = LoggerFactory.getLogger(AlipayController.class);
	
	@RequestMapping(value = "pay_request.html", method = { RequestMethod.GET, RequestMethod.POST })
	public void pay_request(Integer id,Integer cid,HttpServletRequest request, HttpServletResponse response) throws IOException {
		////////////////////////////////////请求参数//////////////////////////////////////
		String uid = CasUtil.getUid(request);
		CreativeOrderModel order = new CreativeOrderModel();
		if(id != null){
			order = creativeOrderService.getById(id);
			if(order ==  null){
				response.getWriter().print("订单不存在");
				return;
			}
		} else {
			if(cid != null){
				CreativeModel creativeModel = creativeService.getCreativeByCid(cid);
				if(creativeModel ==  null){
					response.getWriter().print("创意不存在");
					return;
				}
			    Long time = new Date().getTime();
				String order_num = time.toString()+(int)(Math.random()*10)+(int)(Math.random()*10)+(int)(Math.random()*10);
			    order.setOrder_num(order_num);
			    order.setUid(Integer.parseInt(uid));
			    order.setCid(creativeModel.getCid());
			    order.setCuid(creativeModel.getUid());
			    order.setTitle(creativeModel.getTitle());
			    order.setCdescribe(creativeModel.getCdescribe());
			    order.setCvalue(creativeModel.getCvalue());
			    order.setAutro_instr(creativeModel.getAutro_instr());
			    order.setCover_url(creativeModel.getCover_url());
			    order.setSource_url(creativeModel.getSource_url());
			    creativeOrderService.insert(order);
			}else{
				response.getWriter().print("参数错误");
				return;
			}
		}

		//支付类型
		String payment_type = "1";
		//必填，不能修改
		//服务器异步通知页面路径
		String notify_url = Config.getString("server.host")+"/pay_notify.html";
		//需http://格式的完整路径，不能加?id=123这类自定义参数
		
		//页面跳转同步通知页面路径
		String return_url = Config.getString("server.host")+"/pay_return.html";
		//需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
		
		//卖家支付宝帐户
		String seller_email = new String(AlipayConfig.seller_email.getBytes("ISO-8859-1"),"UTF-8");
		//必填
		
		//商户订单号
		//String out_trade_no = new String(order.getOrder_num().getBytes("ISO-8859-1"),"UTF-8");
		String out_trade_no = order.getOrder_num();
		//商户网站订单系统中唯一订单号，必填
		
		//订单名称
		//String subject = new String(order.getTitle().getBytes("ISO-8859-1"),"UTF-8");
		String subject = order.getTitle();
		//必填
		
		//付款金额
		//String total_fee = new String(order.getCvalue().toString().getBytes("ISO-8859-1"),"UTF-8");
		String total_fee = order.getCvalue().toString();
		//必填
		
		//订单描述
		
		//String body = new String("".getBytes("ISO-8859-1"),"UTF-8");
		String body = "";
		
		//商品展示地址
		//String show_url = new String(("/creative_detail.html?cid="+order.getCid()).getBytes("ISO-8859-1"),"UTF-8");
		String show_url = Config.getString("server.host")+"/creative_detail.html?cid="+order.getCid();
		//需以http://开头的完整路径，例如：http://www.xxx.com/myorder.html
		
		//防钓鱼时间戳
		String anti_phishing_key = "";
		//若要使用请调用类文件submit中的query_timestamp函数
		
		//客户端的IP地址
		String exter_invoke_ip = RequestUtils.getRemoteIp();
		//非局域网的外网IP地址，如：221.0.0.1
		
		
		//////////////////////////////////////////////////////////////////////////////////
		
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("seller_email", seller_email);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", total_fee);
		sParaTemp.put("body", body);
		sParaTemp.put("show_url", show_url);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		
		response.setContentType("text/html; charset=utf-8");
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
		response.getWriter().print(sHtmlText);
	}
	
	@RequestMapping(value = "pay_notify.html", method = { RequestMethod.GET, RequestMethod.POST })
	public void pay_notify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号

		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

		//支付宝交易号

		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

		//交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

		if(AlipayNotify.verify(params)){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					
				//注意：
				//该种交易状态只在两种情况下出现
				//1、开通了普通即时到账，买家付款成功后。
				//2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
				
				CreativeOrderModel order = new CreativeOrderModel();
				CreativeOrderModel orderModel = creativeOrderService.getByNum(out_trade_no); 
				if( orderModel != null && orderModel.getOrder_state() == 0){
					order.setOrder_num(out_trade_no);
					order.setTrade_no(trade_no);
					order.setOrder_state(1);
					creativeOrderService.updateByOrderNum(order);
					CreativeModel creative = creativeService.getCreativeByCid(orderModel.getCid());
					userService.addBalance(creative.getUid(), (float)creative.getCvalue());
				}
				logger.error("Alipay:payNotify:success:TRADE_FINISHED");	
			} else if (trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				logger.error("Alipay:payNotify:success:TRADE_SUCCESS");	
				//注意：
				//该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
				
				CreativeOrderModel order = new CreativeOrderModel();
				CreativeOrderModel orderModel = creativeOrderService.getByNum(out_trade_no);
				if( orderModel != null && orderModel.getOrder_state() == 0){
					order.setOrder_num(out_trade_no);
					order.setTrade_no(trade_no);
					order.setOrder_state(1);
					creativeOrderService.updateByOrderNum(order);
					CreativeModel creative = creativeService.getCreativeByCid(orderModel.getCid());
					userService.addBalance(creative.getUid(), (float)creative.getCvalue());
				}
				
			}

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
				
			//out.println("success");	//请不要修改或删除
			logger.info("Alipay:payNotify:success");
			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			//out.println("fail");
			logger.error("Alipay:payNotify:fail");
		}
	}
	@RequestMapping(value = "pay_return.html", method = { RequestMethod.GET, RequestMethod.POST })
	public void pay_return(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号

		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

		//支付宝交易号

		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

		//交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		
		//计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params);
		response.setContentType("text/html; charset=UTF-8");
		if(verify_result){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				CreativeOrderModel order = creativeOrderService.getByNum(out_trade_no);
				response.sendRedirect("/creative_buy_suc.html?cid="+order.getCid());
			}else{
				response.getWriter().print("支付失败");
			}
			
			//该页面可做页面美工编辑
			//out.println("验证成功<br />");
			response.getWriter().print("验证成功<br />");
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{
			//该页面可做页面美工编辑
			//out.println("验证失败");
			response.getWriter().print("验证失败");
		}
	}
}
